package com.jh3502.helper.function.person.personnew;

import android.app.ActivityOptions;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseActivity;
import com.jh3502.helper.function.listrule.ListRuleChooseBean;
import com.jh3502.helper.function.person.GridImageAddAdapter;
import com.jh3502.helper.function.person.GridImageShowAdapter;
import com.jh3502.helper.function.person.ImageShowActivity;
import com.jh3502.helper.function.person.personlist.PersonListBean;
import com.jh3502.helper.function.person.personsp.PersonSpActivity;
import com.jh3502.helper.utils.Constant;
import com.jh3502.helper.utils.ConstantUtil;
import com.jh3502.helper.utils.PinyinUtil;
import com.jh3502.helper.utils.SpHelper;
import com.jh3502.helper.utils.UploadHelper;
import com.jh3502.helper.utils.Utils;
import com.jh3502.helper.utils.UtilsCode;
import com.jh3502.helper.utils.bluetooth.ConnectEvent;
import com.jh3502.helper.utils.bluetooth.NotifyDataEvent;
import com.jh3502.helper.utils.eventbus.EventBusHelper;
import com.jh3502.helper.utils.eventbus.EventBusMessage;
import com.jh3502.helper.utils.listener.MyFocusChangeListener;
import com.jh3502.helper.view.ActionSheetDialog;
import com.jh3502.helper.view.SnackbarUtil;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.xsnow.event.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cxy.com.validate.SimpleValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.NotNull;

/**
 * @author harisucici
 */
public class PersonNewActivity extends BaseActivity {
    private static final int SELECT_MAX = 3;
    private static final String EMPTY_CODE = "";
    private final static int ISLEFT = 0;
    private final static int ISRIGHT = 1;
    @Nullable
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @Nullable
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @Nullable
    @BindView(R.id.person_new_batch)
    TextView personNewBatch;
    @Nullable
    @Index(0)
    @NotNull(msg = "请输入姓名！")
    @BindView(R.id.person_new_name)
    EditText personNewName;
    @Nullable
    @BindView(R.id.person_new_ruler)
    ImageView personNewRuler;
    @Nullable
    @BindView(R.id.person_new_org)
    EditText personNewOrg;
    @Nullable
    @BindView(R.id.person_new_dep)
    EditText personNewDep;
    @Nullable
    @BindView(R.id.person_new_sex)
    TextView personNewSex;
    @Nullable
    @BindView(R.id.person_new_age)
    EditText personNewAge;
    @Nullable
    @BindView(R.id.person_detail_tall)
    EditText personDetailTall;
    @Nullable
    @BindView(R.id.person_detai_title)
    LinearLayout personDetaiTitle;
    @Nullable
    @BindView(R.id.person_new_image_video_recycler)
    RecyclerView personNewImageVideoRecycler;
    @Nullable
    @BindView(R.id.person_detai_photo)
    LinearLayout personDetaiPhoto;
    @Nullable
    @BindView(R.id.person_new_detail_up_rv)
    RecyclerView personNewDetailUpRv;
    @Nullable
    @BindView(R.id.person_new_detail_down_rv)
    RecyclerView personNewDetailDownRv;
    @Nullable
    @BindView(R.id.person_detail_other)
    EditText personDetailOther;
    @Nullable
    @BindView(R.id.person_detail_mid_waist)
    EditText personDetailMidWaist;
    @Nullable
    @BindView(R.id.person_detail_chest)
    EditText personDetailChest;
    @Nullable
    @BindView(R.id.person_detail_neck)
    EditText personDetailNeck;
    @Nullable
    @BindView(R.id.person_detail_up)
    EditText personDetailUp;
    @Nullable
    @BindView(R.id.person_detail_leg)
    EditText personDetailLeg;
    @Nullable
    @BindView(R.id.person_detail_ass)
    EditText personDetailAss;
    @Nullable
    @BindView(R.id.person_detail_waist)
    EditText personDetailWaist;
    @Nullable
    @BindView(R.id.person_detail_down)
    EditText personDetailDown;
    @Nullable
    @BindView(R.id.person_new_sp)
    View personNewSp;
    @Nullable
    @BindView(R.id.person_new_sp_image)
    ImageView personNewSpImage;
    @Nullable
    @BindView(R.id.person_detail_sp_body_a)
    TextView personDetailSpBodyA;
    @Nullable
    @BindView(R.id.person_detail_sp_stoop)
    TextView personDetailSpStoop;
    @Nullable
    @BindView(R.id.person_detail_sp_body_b)
    TextView personDetailSpBodyB;
    @Nullable
    @BindView(R.id.person_detail_sp_waist_mid)
    TextView personDetailSpWaistMid;
    @Nullable
    @BindView(R.id.person_detail_sp_big_shouder)
    TextView personDetailSpBigShouder;
    @Nullable
    @BindView(R.id.person_detail_sp_flat)
    TextView personDetailSpFlat;
    @Nullable
    @BindView(R.id.person_detail_sp_foot)
    TextView personDetailSpFoot;
    @Nullable
    @BindView(R.id.person_detail_sp_back_ass)
    TextView personDetailSpBackAss;
    @Nullable
    @BindView(R.id.person_detail_sp_back)
    TextView personDetailSpBack;
    @Nullable
    @BindView(R.id.person_detail_sp_mid_waist)
    TextView personDetailSpMidWaist;
    @Nullable
    @BindView(R.id.person_detail_sp_body_f)
    TextView personDetailSpBodyF;
    @Nullable
    @BindView(R.id.person_detail_sp_waist_up)
    TextView personDetailSpWaistUp;
    @Nullable
    @BindView(R.id.person_detail_sp_waist_down)
    TextView personDetailSpWaistDown;
    @Nullable
    @BindView(R.id.person_detail_sp_slash)
    TextView personDetailSpSlash;
    @Nullable
    @BindView(R.id.person_detail_sp_ball)
    TextView personDetailSpBall;
    @Nullable
    @BindView(R.id.person_detail_sp_tran_ball)
    TextView personDetailSpTranBall;
    @Nullable
    @BindView(R.id.person_detail_sp_front)
    TextView personDetailSpFront;
    @BindView(R.id.person_detail_sp_neck)
    TextView personDetailSpNeck;
    @BindView(R.id.person_detail_sp_ass)
    TextView personDetailSpAss;
    @BindView(R.id.person_detail_sp_stomach)
    TextView personDetailSpStomach;
    @NonNull
    private String[] selectData = {"相机", "图片"};
    @NonNull
    private String[] selectSex = {"男", "女"};
    private GridImageAddAdapter mGridImageAdapter;
    private List<PersonListBean> personList;
    @NonNull
    private ArrayList<Map<String, Object>> videoImgData = new ArrayList<>(2);
    private int personNewSexId = -1;
    @Nullable
    private String batchNo;
    private String personId;
    @Nullable
    private String batchTitle;
    @NonNull
    private List<PersonNewBean> editTextList = new ArrayList<>();
    @NonNull
    private List<PersonNewBean> editTextListSp = new ArrayList<>();
    private int clickIndex;
    @Nullable
    private Map<String, Object> personSpList;
    @Nullable
    private PersonListBean personMap;
    private List<PersonNewBean> editTextListUp = new ArrayList<>();
    private List<PersonNewBean> editTextListDown = new ArrayList<>();
    @NonNull
    private List<String> listUp = new ArrayList<>(2);
    @NonNull
    private List<String> listDown = new ArrayList<>(2);
    private int focusNormal = -1;
    private PersonNewAdapter mAdapterUp, mAdapterDown;
    private boolean isSpOpen = false;
    private int switchRecycle = 0;//切换左右

    @Override
    protected int setViewId() {
        return R.layout.activity_person_new;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onBackPressed() {
        // 没名字就不存了
        Validate.check(this, new SimpleValidateResult() {
            @Override
            public void onValidateSuccess() {
                personList.add(personMap);
                SpHelper.getInstance().setPersonList(batchNo, personList);
//                EventBusHelper.sendEventBusMsg(EventBusHelper.PERSONNEW_INDEX_NORMAL, 0 + "");
                Log.e("3502", SpHelper.getInstance().getBatchList().toString());
            }

            @Override
            public void onValidateError(@NonNull String msg, EditText editText) {
                showShortToast(msg, SnackbarUtil.ALERT);
            }
        });
        super.onBackPressed();
    }

    @Override
    protected void initView() {

        toolbar.setTitle("");
        batchNo = getIntent().getExtras().getString("batchNo");
        batchTitle = getIntent().getExtras().getString("batchTitle");
        personNewBatch.setText(batchTitle);
        // 初始化控件
        initEditTextList();
        initEditTextListSp();

        // 初始化基本量体控件  部位编号
        String updress = SpHelper.getInstance().getString(Constant.CHOSEN_UPDERSS);
        String downdress = SpHelper.getInstance().getString(Constant.CHOSEN_DOWNDERSS);


        if (!"[]".equals(updress)) {
            editTextListUp = initEditTextListUpAll(updress);
            StaggeredGridLayoutManager layoutManagerUp = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
            mAdapterUp = new PersonNewAdapter
                    (this, editTextListUp, listUp, editTextList.size());
            personNewDetailUpRv.setLayoutManager(layoutManagerUp);
            personNewDetailUpRv.setAdapter(mAdapterUp);
            // 重新定位
            mAdapterUp.setButtonSetOnclick(position -> {
                switchRecycle = ISLEFT;
                focusNormal = position + editTextList.size();
            });


        }
        if (!"[]".equals(downdress)) {
            editTextListDown = initEditTextListDownAll(downdress);
            StaggeredGridLayoutManager layoutManagerDown = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
            mAdapterDown = new PersonNewAdapter
                    (this, editTextListDown, listDown, editTextList.size() + editTextListUp.size());
            personNewDetailDownRv.setLayoutManager(layoutManagerDown);
            personNewDetailDownRv.setAdapter(mAdapterDown);
            // 重新定位
            mAdapterDown.setButtonSetOnclick(position -> {
                switchRecycle = ISRIGHT;
                focusNormal = position + listUp.size() + editTextList.size();
            });
        }


        if (getIntent().getIntExtra("type", -1) == Constant.PERSON_NEW_ACTIVITY) {//由新建跳转
            toolbarTitle.setText("添加人员信息" + " " + getIntent().getStringExtra("title"));
            personId = UUID.randomUUID().toString();
            mSpeaker.speeking("添加人员信息" + " " + getIntent().getStringExtra("title"));
        } else if (getIntent().getIntExtra("type", -1) == Constant.PERSON_DETAIL_ACTIVITY) {//已有花名册
            toolbarTitle.setText("查看人员信息" + " " + getIntent().getStringExtra("title"));
            personId = getIntent().getStringExtra("pno");
            personList = SpHelper.getInstance().getPersonList(batchNo);
            // 量体数据
            personMap = getPersonDetail(personId, personList);
            personNewOrg.setText(personMap.getOrg());
            personNewDep.setText(personMap.getDep());
            personNewName.setText(personMap.getName());
            personNewSexId = personMap.getSex();
            personNewSex.setText(selectSex[personNewSexId]);
            personNewAge.setText(personMap.getAge());
//            initImgRecycler(personMap.getPhotos());
            // 上下衣控件赋值
            Map<String, Object> ltDataDo = Utils.getInstance().jso2map(new Gson().toJson(personMap.getLtDataDO()));
            personDetailTall.setText((String) ltDataDo.get("tall"));
            List<String> listUpTemp = new ArrayList<>(2);
            List<String> listDownTemp = new ArrayList<>(2);
            for (int i = 0; i < editTextListUp.size(); i++) {
                String s = editTextListUp.get(i).getIndex();
                listUpTemp.add((String) ltDataDo.get(editTextListUp.get(i).getIndex()));
            }
            for (int i = 0; i < editTextListDown.size(); i++) {
                String s = editTextListDown.get(i).getIndex();
                listDownTemp.add((String) ltDataDo.get(editTextListDown.get(i).getIndex()));
            }
            listUp.clear();
            listDown.clear();

            // 赋值
            if (listUpTemp.size() > 0) {
                listUp.addAll(listUpTemp);
                mAdapterUp.notifyDataSetChanged();
            }
            if (listDownTemp.size() > 0) {
                listDown.addAll(listDownTemp);
                mAdapterDown.notifyDataSetChanged();

            }
            setTextView(editTextListSp, personMap.getLtDataDO());
            personNewOrg.setKeyListener(null);
            personNewDep.setKeyListener(null);
            personNewName.setKeyListener(null);
            personNewSex.setOnClickListener(null);
            personNewAge.setKeyListener(null);
        }

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        mPersonNewPresenter = new PersonNewPresenter();
//        mPersonNewPresenter.setPersonNewView(this);
        initBlueTooth();

    }


    @Override
    protected void initData() {
        // 取得特体字典
        personSpList = SpHelper.getInstance().getSp();
        if (getIntent().getIntExtra("type", -1) == Constant.PERSON_DETAIL_ACTIVITY) {
            //获取身高焦点,开始量体
            mSpeaker.speeking("开始量体");
            personDetailTall.setOnFocusChangeListener(
                    new MyFocusChangeListener(this, "身高", -1));
            personDetailTall.requestFocus();
            return;
        }
        personList = SpHelper.getInstance().getPersonList(batchNo);
        if (personList == null) {
            personList = new ArrayList<>(2);
        }
        personNewImageVideoRecycler.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        mGridImageAdapter = new GridImageAddAdapter(this, getOnAddPicClickListener());
        mGridImageAdapter.setSelectMax(SELECT_MAX);
        personNewImageVideoRecycler.setAdapter(mGridImageAdapter);
        mGridImageAdapter.setList(videoImgData);
        mGridImageAdapter.setOnItemClickListener((position, v) -> {
            if (position != videoImgData.size()) {
                int type = Integer.parseInt((String) videoImgData.get(position).get("type"));
                switch (type) {
                    case ConstantUtil.TYPE_FILE_IMG:
                        File file = new File((String) videoImgData.get(position).get("name"));
                        Intent it = new Intent(Intent.ACTION_VIEW);
                        Uri mUri = Uri.parse("file://" + file.getPath());
                        it.setDataAndType(mUri, "image/*");
                        startActivity(it);
                        break;
                    default:
                }
            }
        });


//        //全部初始化完成后开始接受数据
//        personDetailTall.requestFocus();
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (!Utils.getInstance().isFastDoubleClick()) {
            //基本信息
            switch (item.getItemId()) {
                case android.R.id.home:
                    onBackPressed();
                    break;
                case R.id.action_edit:
                    supportInvalidateOptionsMenu();
                    mSpeaker.speeking("编辑");
                    initBlueTooth();
                    break;
                case R.id.action_save:
                    supportInvalidateOptionsMenu();
                    Validate.check(this, new SimpleValidateResult() {
                        @Override
                        public void onValidateSuccess() {
                            ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(PersonNewActivity.this);
                            actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
                            actionSheetDialogType.addSheetItem("结束量体", R.color.green, () -> {
                                doSave();
                                mSpeaker.speeking("量体结束");
                            });
                            actionSheetDialogType.show();
                        }

                        @Override
                        public void onValidateError(@NonNull String msg, EditText editText) {
                            showShortToast(msg, SnackbarUtil.ALERT);
                        }
                    });
                    break;
                default:
                    break;
            }
        }

        return true;
    }

    private void doSave() {
        personMap = new PersonListBean();
        personMap.setPno(personId);
        personMap.setOnline(Constant.LOCAL);
        personMap.setBatno(batchNo);
        personMap.setOrg(personNewOrg.getText().toString().trim());
        personMap.setDep(personNewDep.getText().toString().trim());
        personMap.setName(personNewName.getText().toString().trim());
        personMap.setNamePinyin(PinyinUtil.getInstance().getPinyin(personNewName.getText().toString().trim().substring(0, 1)));
        personMap.setAge(personNewAge.getText().toString().trim());
        personMap.setSex(personNewSexId);
        personMap.setCheck(false);
//        personListBean.setPhotos(new Gson().toJson(videoImgData));
        personMap.setSpOpen(isSpOpen);//判断特体
        Map<String, Object> personDetailMap = new HashMap<>(2);
        personDetailMap.put("tall", personDetailTall.getText().toString());
        for (int i = 0; i < editTextListUp.size(); i++) {
            PersonNewAdapter.ViewHolder viewholder =
                    (PersonNewAdapter.ViewHolder) personNewDetailUpRv.findViewHolderForAdapterPosition(i);
            personDetailMap.put(editTextListUp.get(i).getIndex(),
                    viewholder.itemPersonNewContent.getText().toString().trim());
        }

        for (int i = 0; i < editTextListDown.size(); i++) {
            PersonNewAdapter.ViewHolder viewholder =
                    (PersonNewAdapter.ViewHolder) personNewDetailDownRv.findViewHolderForAdapterPosition(i);
            personDetailMap.put(editTextListDown.get(i).getIndex(),
                    viewholder.itemPersonNewContent.getText().toString().trim());
        }
        personDetailMap.put("updress", personDetailUp.getText().toString());
        personDetailMap.put("downdress", personDetailDown.getText().toString());
        personDetailMap.put("updresshint", personDetailUp.getHint().toString());
        personDetailMap.put("downdresshint", personDetailDown.getHint().toString());
        personDetailMap.put("other", personDetailOther.getText().toString());

        for (PersonNewBean personNewBean : editTextListSp) {
            personDetailMap.put(personNewBean.getIndex(), personNewBean.getTextview().getText().toString().trim());
        }

        personMap.setLtDataDO(new Gson().fromJson(new Gson().toJson(personDetailMap), PersonListBean.PersonDetailBean.class));

    }


    private void initEditTextList() {
        editTextList.add(new PersonNewBean(personDetailMidWaist, "净中腰围", "midwaist"));
        editTextList.add(new PersonNewBean(personDetailChest, "净胸围", "chest"));
        editTextList.add(new PersonNewBean(personDetailNeck, "领围", "neck"));
        editTextList.add(new PersonNewBean(personDetailLeg, "裤长", "leg"));
        editTextList.add(new PersonNewBean(personDetailAss, "臀围", "ass"));
        editTextList.add(new PersonNewBean(personDetailWaist, "腰围", "waist"));
        initEditTextListener();
    }

    private void initEditTextListSp() {
        editTextListSp.add(new PersonNewBean(personDetailSpBodyA, "总身长", "spbodya"));
        editTextListSp.add(new PersonNewBean(personDetailSpMidWaist, "中腰", "spmidwaist"));
        editTextListSp.add(new PersonNewBean(personDetailSpStoop, "驼背", "spstoop"));
        editTextListSp.add(new PersonNewBean(personDetailSpBodyF, "前身长", "spbodyf"));
        editTextListSp.add(new PersonNewBean(personDetailSpBodyB, "后身长", "spbodyb"));
        editTextListSp.add(new PersonNewBean(personDetailSpWaistUp, "上腰围", "spwaistup"));
        editTextListSp.add(new PersonNewBean(personDetailSpWaistMid, "中腰围", "spwaistmid"));
        editTextListSp.add(new PersonNewBean(personDetailSpWaistDown, "下摆围", "spwaistdown"));
        editTextListSp.add(new PersonNewBean(personDetailSpNeck, "脖子短粗", "spneck"));
        editTextListSp.add(new PersonNewBean(personDetailSpBigShouder, "大肩宽", "spbigshouder"));
        editTextListSp.add(new PersonNewBean(personDetailSpSlash, "溜肩", "spslash"));
        editTextListSp.add(new PersonNewBean(personDetailSpFlat, "平肩", "spflat"));
        editTextListSp.add(new PersonNewBean(personDetailSpBall, "下裆", "spball"));
        editTextListSp.add(new PersonNewBean(personDetailSpFoot, "脚口", "spfoot"));
        editTextListSp.add(new PersonNewBean(personDetailSpTranBall, "横裆", "sptranball"));
        editTextListSp.add(new PersonNewBean(personDetailSpBackAss, "后开门", "spbackass"));
        editTextListSp.add(new PersonNewBean(personDetailSpAss, "翘臀体", "spass"));
        editTextListSp.add(new PersonNewBean(personDetailSpStomach, "小腹凸体", "spstomach"));
        editTextListSp.add(new PersonNewBean(personDetailSpFront, "前撬", "spfront"));
        editTextListSp.add(new PersonNewBean(personDetailSpBack, "后撬", "spback"));
        initEditTextListenerSp();
    }

    private void initEditTextListener() {
        int i = 0;
        for (PersonNewBean personNewBean : editTextList) {
            personNewBean.getEditText().setOnFocusChangeListener(
                    new MyFocusChangeListener(this, personNewBean.getName(), i));
            i++;
        }


    }

    private void initEditTextListenerSp() {
        for (int i = 0; i < editTextList.size(); i++) {
            PersonNewBean personNewBean = editTextListSp.get(i);
            int finalI = i;
            personNewBean.getTextview().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int type = getIntent().getIntExtra("type", -1);
                    if (type == Constant.PERSON_NEW_ACTIVITY || (type == Constant.PERSON_DETAIL_ACTIVITY)) {
                        clickIndex = finalI;
                        Intent intent = new Intent(PersonNewActivity.this, PersonSpActivity.class);
                        intent.putExtra("name", personNewBean.getIndex());
                        intent.putExtra("nameList", (String) personSpList.get(personNewBean.getIndex()));
                        startActivityForResult(intent, Constant.PERSON_SP);
                    }
                }
            });

        }
    }

    @Override
    public void onEventMainThread(@NonNull EventBusMessage eventBusMessage) {
        if (eventBusMessage.getCode() == EventBusHelper.PERSONNEW_INDEX_NORMAL) {
            focusNormal = Integer.parseInt(eventBusMessage.getMessage());
        }
    }


    @Subscribe
    public void showConnectedDevice(@Nullable ConnectEvent event) {
        if (event != null) {
            if (event.isSuccess()) {
                showShortToast("E尺连接成功");
                Glide.with(this).load(R.drawable.ic_visibility_black_24dp).into(personNewRuler);
                if (event.getDeviceMirror() != null && event.getDeviceMirror().getBluetoothGatt() != null) {
                    displayGattServices(event.getDeviceMirror().getBluetoothGatt().getServices());
                }
                getUuid(mJh3502HelperApplication.getExtraDevice());
            } else {
                if (event.isDisconnected()) {
                    showShortToast("已断开连接");
                    Glide.with(this).load(R.drawable.ic_visibility_off_black_24dp).into(personNewRuler);
                } else {
                    showShortToast("连接失败");
                    Glide.with(this).load(R.drawable.ic_visibility_off_black_24dp).into(personNewRuler);
                }
                mJh3502HelperApplication.setExtraDevice(null);
                clearUI();
            }
        }
    }

    @Subscribe
    public void showDeviceNotifyData(@Nullable NotifyDataEvent event) {
        double temp;
        BluetoothLeDevice mDeviceTemp = mJh3502HelperApplication.getExtraDevice();
        if (event != null && event.getData() != null && event.getBluetoothLeDevice() != null
                && event.getBluetoothLeDevice().getAddress().equals(mDeviceTemp.getAddress())) {
            temp = Utils.getInstance().getRuler(event, mDeviceTemp);
            if (temp == -1) {
                return;
            }
            PersonNewAdapter.ViewHolder viewholder;
            if (focusNormal == -1) {
                personDetailTall.setText(Double.toString(temp));
            } else if (focusNormal > -1 && focusNormal < editTextList.size()) {
                editTextList.get(focusNormal).getEditText().setText(Double.toString(temp));
            } else {
                if (switchRecycle == ISLEFT) {
                    viewholder = (PersonNewAdapter.ViewHolder) personNewDetailUpRv.
                            findViewHolderForAdapterPosition(focusNormal - editTextList.size());
                } else {
                    viewholder = (PersonNewAdapter.ViewHolder) personNewDetailDownRv.
                            findViewHolderForAdapterPosition(focusNormal - editTextList.size() - listUp.size());
                }
                if (temp == 0 || temp == 1.4) {
                    viewholder.itemPersonNewContent.setText("");
                } else {
                    viewholder.itemPersonNewContent.setText(Double.toString(temp));
                }
            }
            focusNormal++;


            if (focusNormal > -1 && focusNormal < editTextList.size()) {
                editTextList.get(focusNormal).getEditText().requestFocus();
            } else if (focusNormal >= editTextList.size()) {
                if (focusNormal - editTextList.size() < listUp.size()) {
                    switchRecycle = ISLEFT;
                } else {
                    switchRecycle = ISRIGHT;
                }
                if (switchRecycle == ISLEFT) {
                    viewholder = (PersonNewAdapter.ViewHolder) personNewDetailUpRv.
                            findViewHolderForAdapterPosition(focusNormal - editTextList.size());
                } else {
                    Log.e("3502", "focusNormal:" + focusNormal);
                    viewholder = (PersonNewAdapter.ViewHolder) personNewDetailDownRv.
                            findViewHolderForAdapterPosition(focusNormal - editTextList.size() - listUp.size());
                    Log.e("3502", "focusNormal:" + focusNormal);
                }
                // 测量到最后一个还原第一个位置
                if (focusNormal == listUp.size() + listDown.size() + editTextList.size()) {
                    switchRecycle = ISLEFT;
                    focusNormal = 0;
                    editTextList.get(focusNormal).getEditText().requestFocus();
                    return;
                }
                viewholder.itemPersonNewContent.requestFocus();
            }


        }
    }


    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {
    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }


    private List<PersonNewBean> initEditTextListUpAll(String s) {
        ArrayList<String> updressList = Utils.getInstance().jsa2list1(s);
        List<PersonNewBean> editTextListUpAll = new ArrayList<>();
        String[] batchUpName = getResources().getStringArray(R.array.batch_normal_name);
        String[] batchUp = getResources().getStringArray(R.array.batch_normal);

        int i = 0;
        for (String name : batchUpName) {
            editTextListUpAll.add(new PersonNewBean(batchUpName[i], batchUp[i]));
            i++;
        }

        for (String n : updressList) {
            editTextListUp.add(editTextListUpAll.get(Integer.parseInt(n)));
        }

        return editTextListUp;
    }

    private List<PersonNewBean> initEditTextListDownAll(String s) {
        ArrayList<String> downdressList = Utils.getInstance().jsa2list1(s);
        List<PersonNewBean> editTextListDownAll = new ArrayList<>();
        String[] batchDownName = getResources().getStringArray(R.array.batch_sp_name);
        String[] batchDown = getResources().getStringArray(R.array.batch_sp);
        int i = 0;
        for (String name : batchDownName) {
            editTextListDownAll.add(new PersonNewBean(batchDownName[i], batchDown[i]));
            i++;
        }

        for (String n : downdressList) {
            editTextListDown.add(editTextListDownAll.get(Integer.parseInt(n)));
        }

        return editTextListDown;
    }

//    @OnClick(R.id.item_person_next)
//    public void onItemPersonNextClicked() {
//        PersonNewAdapter.ViewHolder viewholder = (PersonNewAdapter.ViewHolder) personNewDetailUpRv.findViewHolderForAdapterPosition(focusNormal);
//        viewholder.item_person_new_content.requestFocus();
//    }

    private GridImageAddAdapter.onAddPicClickListener getOnAddPicClickListener() {
        return (type, position) -> {
            switch (type) {
                case 0:
                    showSelectDialog();
                    break;
                case 1:
                    videoImgData.remove(position);
                    mGridImageAdapter.notifyItemRemoved(position);
                    break;
                default:
            }
        };
    }

    public void showSelectDialog() {
        ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
        actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
        for (int i = 0; i < selectData.length; i++) {
            String title = selectData[i];
            int finalI = i;
            actionSheetDialogType.addSheetItem(title, R.color.green,
                    () -> {
                        switch (finalI) {
                            case 0:
                                saveImageFromCamera(batchNo);
                                break;
                            case 1:
                                chooseLocImage();
                                break;
                            default:
                                break;
                        }
                    });
        }
        actionSheetDialogType.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path;
            switch (requestCode) {
                case Constant.PERSON_SP:
                    String s1 = data.getStringExtra("addsub");
                    String s2 = data.getStringExtra("content");
                    editTextListSp.get(clickIndex).getTextview().setText(s2 + s1);
                    break;
                case Constant.CONNECT_BLUE_TOOTH:
                    initBlueTooth();
                    break;
                case Constant.REQUEST_CODE_IMAGE:
                    path = UploadHelper.getInstance().getImageAbsolutePath(this, data.getData());
//                    mPersonNewPresenter.sendImageMsg(path);
                    HashMap<String, Object> map = new HashMap<>(2);
                    map.put("path", path);
                    videoImgData.add(map);
                    mGridImageAdapter.notifyItemChanged(videoImgData.size() - 1);
                    break;
                case Constant.REQUEST_CODE_CAMARE:
                    HashMap<String, Object> mapCam = new HashMap<>(2);
                    mapCam.put("path", mCamareFile.getPath());
                    videoImgData.add(mapCam);
                    mGridImageAdapter.notifyItemChanged(videoImgData.size() - 1);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void responseError(int code, @NonNull String msg) {
        showShortToast(msg);
    }


    @OnClick(R.id.person_new_sex)
    public void onPersonNewSexClicked() {
        ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
        actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
        for (int i = 0; i < selectSex.length; i++) {
            String title = selectSex[i];
            int finalI = i;
            actionSheetDialogType.addSheetItem(title, R.color.green,
                    () -> {
                        personNewSex.setText(selectSex[finalI]);
                        personNewSexId = finalI;
//                        personDetail1Person.setVisibility(View.VISIBLE);
//                        if (personNewSexId == 0) {
//                            personDetail1Male.setVisibility(View.VISIBLE);
//                            personDetail1Female.setVisibility(View.INVISIBLE);
//                        } else if (personNewSexId == 1) {
//                            personDetail1Male.setVisibility(View.INVISIBLE);
//                            personDetail1Female.setVisibility(View.VISIBLE);
//                        }
                    });
        }
        actionSheetDialogType.show();
    }

    @OnTextChanged(value = R.id.person_detail_chest, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedChest(CharSequence s, int start, int before, int count) {
        Validate.check(this, new SimpleValidateResult() {
            @Override
            public void onValidateSuccess() {
//                personDetailUpDown(personNewSexId, true);
            }
        });

    }

    @OnTextChanged(value = R.id.person_detail_waist, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedWaist(CharSequence s, int start, int before, int count) {
        Validate.check(this, new SimpleValidateResult() {
            @Override
            public void onValidateSuccess() {
//                personDetailUpDown(personNewSexId, false);
            }
        });

    }

    @NonNull
    private String personDetailUpDown(int sexID, boolean isUp) {
        StringBuffer dataAll = new StringBuffer();
        List<Integer> tallIndexTemp = new ArrayList<>(2);
        List<Integer> tallIndex = new ArrayList<>(2);

        if (isUp) {
            if (personDetailChest.getText().toString().trim().length() < 2) {
                return EMPTY_CODE;
            }
        } else {
            if (personDetailWaist.getText().toString().trim().length() < 2) {
                return EMPTY_CODE;
            }
        }
        String tall = personDetailTall.getText().toString().trim();
        if ("".equals(tall)) {
            return EMPTY_CODE;
        }
//        String tall = "164";
        // 取得任务单男女号型规则(数组)
        String[] maleId = getIntent().getStringExtra("maleId").split(",");
        String[] femaleId = getIntent().getStringExtra("femaleId").split(",");

        List<ListRuleChooseBean> jSonS = new ArrayList<>(2);
        if (maleId == null || femaleId == null) {
            return EMPTY_CODE;
        }
        // 取到 ID 对应的库
        if (sexID == 0) {
            for (String s : maleId) {
                jSonS.add(getSexLib(s, 0));
            }
        } else {
            for (String s : femaleId) {
                jSonS.add(getSexLib(s, 1));
            }
        }
        if (jSonS.isEmpty()) {
            return EMPTY_CODE;
        }
        for (ListRuleChooseBean listRuleChooseBean : jSonS) {//适配
            //  取得身高索引
            tallIndexTemp = UtilsCode.getInstance().getRangeIndex(listRuleChooseBean.getTalllist(), tall);
        }


        for (ListRuleChooseBean listRuleChooseBean : jSonS) {//适配
            StringBuffer tallData = new StringBuffer();
            if (tallIndexTemp.isEmpty()) {
                return EMPTY_CODE;
            }
            int ruleType = listRuleChooseBean.getType();
            if (ruleType == Constant.SUIT_RULE_ABC) {
                String chest = personDetailChest.getText().toString();
                if (TextUtils.isEmpty(chest)) {
                    return EMPTY_CODE;
                }
                String waist = personDetailWaist.getText().toString();
                if (TextUtils.isEmpty(waist)) {
                    return EMPTY_CODE;
                }

//                String chest = "110";
//                String waist = "100";
                int sub = Integer.parseInt(chest) - Integer.parseInt(waist);
                if (sub < 0) {
                    return EMPTY_CODE;
                }
                Map<String, Object> mapABC = new HashMap(2);
                if (sexID == 0) {
                    mapABC = Utils.getInstance().jso2map(SpHelper.getInstance().getLtShapeRuleMale());
                } else if (sexID == 1) {
                    mapABC = Utils.getInstance().jso2map(SpHelper.getInstance().getLtShapeRuleFemale());
                }
                String[] stringA = ((String) mapABC.get("A")).split("~");
                String[] stringB = ((String) mapABC.get("B")).split("~");
                String[] stringC = ((String) mapABC.get("C")).split("~");
                String[] stringY = ((String) mapABC.get("Y")).split("~");
                String sizeABC = "";
                if (sub >= Integer.parseInt(stringA[0]) && sub <= Integer.parseInt(stringA[1])) {
                    sizeABC = "A";
                } else if (sub >= Integer.parseInt(stringB[0]) && sub <= Integer.parseInt(stringB[1])) {
                    sizeABC = "B";
                } else if (sub >= Integer.parseInt(stringC[0]) && sub <= Integer.parseInt(stringC[1])) {
                    sizeABC = "C";
                } else if (sub >= Integer.parseInt(stringY[0]) && sub <= Integer.parseInt(stringY[1])) {
                    sizeABC = "Y";
                    Log.e("3502", "Y");
                }
                int index = 0;
                for (int dataIndex : tallIndexTemp) {
                    ListRuleChooseBean.TalldetailBean talldetailBean =
                            listRuleChooseBean.getTalldetail().get(dataIndex);
                    if (talldetailBean.getTall().contains(sizeABC)) {
                        tallIndex.add(dataIndex);
                    }
                    index++;
                }
            } else {//通常的
                tallIndex.addAll(tallIndexTemp);
            }//endif
            if (tallIndex.isEmpty()) {
                return EMPTY_CODE;
            }
            if (isUp) {// 上衣
                for (int dataIndex : tallIndex) {
                    // 量体数据
                    ListRuleChooseBean.TalldetailBean talldetailBean =
                            listRuleChooseBean.getTalldetail().get(dataIndex);
                    List<Integer> chestIndex = UtilsCode.getInstance().getRangeIndex(talldetailBean.getChestRange(),
                            personDetailChest.getText().toString().trim());
                    Log.e("3502", "chestIndex:" + chestIndex.toString());

                    String[] upDress = talldetailBean.getUpdress().get(chestIndex.get(0)).split(",");
                    if (ruleType == Constant.SUIT_RULE_ELEC_NORMAL) {//南方电网
                        // tallData.append(talldetailBean.getTall()+"/"+ upDress[0]+" ");
                    } else {
                        tallData.append(talldetailBean.getTall() + "/" + upDress[0] + " ");
                    }
                }
            } else {// 下衣
                if (ruleType == Constant.SUIT_RULE_ELEC_SHIRT) {
                    // 南方电网衬衣
                } else if (ruleType == Constant.SUIT_RULE_DOUBLE) {
                    // 上下衣同号
                } else if (ruleType == Constant.SUIT_RULE_ELEC_COLD) {
                    // 南方电网防寒服
                } else if (ruleType == Constant.SUIT_RULE_SINGAL) {
                    // 单品衬衣
                } else {
                    for (int dataIndex : tallIndex) {
                        // 量体数据
                        ListRuleChooseBean.TalldetailBean talldetailBean =
                                listRuleChooseBean.getTalldetail().get(dataIndex);
                        List<Integer> waistIndex = UtilsCode.getInstance().getRangeIndex(talldetailBean.getWaistRange(),
                                personDetailWaist.getText().toString().trim());
                        Log.e("3502", "waistIndex:" + waistIndex.toString());

                        String[] downDress = talldetailBean.getDowndress().get(waistIndex.get(0)).split(",");
                        if (ruleType == Constant.SUIT_RULE_ELEC_NORMAL) {//南方电网
//                        tallData.append(talldetailBean.getTall()+"/"+ downDress[0]+" ");
                        } else {
                            tallData.append(talldetailBean.getTall() + "/" + downDress[0] + " ");
                        }
                    }
                }

            }
            // 多号型 多结果
            dataAll.append(tallData);
            dataAll.append("&&");
        }


        return dataAll.toString();
    }

    @OnClick(R.id.toolbar_title)
    public void onToolbarTitleClicked() {
        initBlueTooth();
    }

    @Nullable
    private ListRuleChooseBean getSexLib(@NonNull String id, int sex) {
        ArrayList<Map<String, Object>> sexList = new ArrayList<>(2);
        if (sex == 0) {//根据性别取得规则 list
            sexList = Utils.getInstance().jsa2list(SpHelper.getInstance().getListltruleMale());
        } else if (sex == 1) {
            sexList = Utils.getInstance().jsa2list(SpHelper.getInstance().getListltruleFemale());
        }
        ListRuleChooseBean listRuleChooseBean = null;
        for (Map<String, Object> map : sexList) {
            if (id.equals(map.get("id"))) {
                listRuleChooseBean =
                        new Gson().fromJson(Utils.getInstance().jsa2list1((String) map.get("ltRuleDO")).get(0), ListRuleChooseBean.class);
                listRuleChooseBean.setName((String) map.get("name"));
                listRuleChooseBean.setType(Integer.parseInt((String) map.get("type")));

            }
        }
        return listRuleChooseBean;
    }

    @Nullable
    private PersonListBean getPersonDetail(String personId, List<PersonListBean> personList) {
        // 取出此人的map后移除
        PersonListBean personTemp = null;
        for (int i = 0; i < personList.size(); i++) {
            if (personList.get(i).getPno().equals(personId)) {
                personTemp = personList.get(i);
                personList.remove(i);
            }
        }

        return personTemp;
    }

    private void setEditText(List<PersonNewBean> personNewBeans, PersonListBean.PersonDetailBean personDetailBean) {
//        Map<String, Object> map = Utils.getInstance().jso2map(new Gson().toJson(personDetailBean));
//        for (int i = 0; i < PersonNewBeans.size(); i++) {
//            PersonNewBeans.get(i).getEditText().setText((String) map.get(PersonNewBeans.get(i).getIndex()));
//        }
//
//        personDetail1NeckTv.setText(personDetail1Neck.getText().toString().trim());
//        personDetail1ChestTv.setText(personDetail1Chest.getText().toString().trim());
//        personDetail1WaistTv.setText(personDetail1Waist.getText().toString().trim());
//        personDetail1AssTv.setText(personDetail1Ass.getText().toString().trim());
//
//        personDetail1Up.setText((String) map.get("updress"));
//        personDetail1Down.setText((String) map.get("downdress"));
//        if (map.get("updresshint") != null) {
//            personDetail1Up.setHint((String) map.get("updresshint"));
//        }
//        if (map.get("downdresshint") != null) {
//            personDetail1Down.setHint((String) map.get("downdresshint"));
//        }
//        personDetail1Other.setText((String) map.get("other"));
    }

    private void setTextView(List<PersonNewBean> personNewBeans, PersonListBean.PersonDetailBean personDetailBean) {
        Map<String, Object> map = Utils.getInstance().jso2map(new Gson().toJson(personDetailBean));
        for (int i = 0; i < personNewBeans.size(); i++) {
            personNewBeans.get(i).getTextview().setText((String) map.get(personNewBeans.get(i).getIndex()));
        }
    }

    private void initImgRecycler(String photo) {
        ArrayList<Map<String, Object>> photos = Utils.getInstance().jsa2list(photo);
        GridImageShowAdapter mGridImageShowAdapter = new GridImageShowAdapter(this, photos);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
        personNewImageVideoRecycler.setLayoutManager(layoutManager);
        personNewImageVideoRecycler.setAdapter(mGridImageShowAdapter);

        mGridImageShowAdapter.setOnItemClickListener(s -> {
            View view = personNewImageVideoRecycler.getChildAt(Integer.parseInt(s));
            ImageView item_only_img = view.findViewById(R.id.item_only_img);
            Intent intent = new Intent(this, ImageShowActivity.class);
            intent.putExtra("path", (String) photos.get(Integer.parseInt(s)).get("path"));
            if (Build.VERSION.SDK_INT > 20) {
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this, item_only_img, "header").toBundle());
            } else {
                startActivity(intent);
            }
        });
    }


    @OnClick(R.id.person_new_sp_image)
    public void onPersonNewSpImageClicked() {
        personNewSp.setVisibility(View.VISIBLE);
        personDetailSpBodyA.requestFocus();
        isSpOpen = true;
    }


}
